package fu.capstone.hanoicityguide.presentation.fragment.home;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SearchView;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.home.HomeBO;
import fu.capstone.hanoicityguide.business.bo.home.HomeBOImp;
import fu.capstone.hanoicityguide.business.model.Category;
import fu.capstone.hanoicityguide.business.model.Place;
import fu.capstone.hanoicityguide.presentation.adapter.ListPlaceAdapter;
import fu.capstone.hanoicityguide.presentation.fragment.attraction.DetailAttractionFragment;
import fu.capstone.hanoicityguide.presentation.fragment.hotel.DetailHotelFragment;
import fu.capstone.hanoicityguide.presentation.fragment.nightlife.DetailNightLifeFragment;
import fu.capstone.hanoicityguide.presentation.fragment.restaurant.DetailRestaurantFragment;

@SuppressLint("ValidFragment")
public class ListPlaceFragment extends Fragment implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener {

	private HomeBO homeBO;
	private ArrayList<Place> arrPlace;
	private String[] arrType;
	private ArrayList<Category> arrCategory = null;
	private ArrayList<String> filter;
	private String sorter;
	private ListPlaceAdapter placeAdapter = null;
	private ListView listPlace = null;
	private SearchView searchView;
	private String keyword;
	private boolean[] itemChecked;
	private boolean[] oldChecked;
	private DrawerLayout drawer;

	public ListPlaceFragment(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// init
		View listPlaceFragment = inflater.inflate(R.layout.fragment_list_place,
				container, false);
		try {
			setHasOptionsMenu(true);
			homeBO = new HomeBOImp(container.getContext());
			listPlace = (ListView) listPlaceFragment
					.findViewById(R.id.listPlace);

			// set filter and sorter
			filter = new ArrayList<String>();
			setKeyword("");
			// setFilter("All");
			setSorter(getResources().getStringArray(R.array.sorter_items)[0]);

			// get category
			arrCategory = new ArrayList<Category>();
			arrCategory = homeBO.getListCategory("");
			arrType = new String[5];
			arrType[0] = "All";
			for (int i = 0; i < arrCategory.size(); i++) {
				arrType[(i + 1)] = arrCategory.get(i).getCategoryName();
			}
			filter.add("All");
			for (int i = 0; i < arrCategory.size(); i++) {
				filter.add(arrCategory.get(i).getCategoryName());
			}

			// init checked item
			itemChecked = new boolean[arrType.length];
			for (int i = 0; i < itemChecked.length; i++) {
				itemChecked[i] = true;
			}

			// get all list place
			arrPlace = new ArrayList<Place>();
			arrPlace = homeBO.searchPlace(getKeyword(), getFilter(),
					getSorter());

			placeAdapter = new ListPlaceAdapter(getActivity(),
					R.layout.adapter_list_place, arrPlace);

			// set listview adapter and create event for items click
			listPlace.setAdapter(placeAdapter);

			listPlace.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// call Detail Fragment of Place
					Fragment browsePlace = null;
					switch (arrPlace.get(position).getCategory()) {
					case "Attraction":
						browsePlace = new DetailAttractionFragment(arrPlace
								.get(position).getId());
						break;
					case "Hotel":
						browsePlace = new DetailHotelFragment(arrPlace.get(
								position).getId());
						break;
					case "Restaurant":
						browsePlace = new DetailRestaurantFragment(arrPlace
								.get(position).getId());
						break;
					case "Nightlife":
						browsePlace = new DetailNightLifeFragment(arrPlace.get(
								position).getId());
						break;
					default:
						break;
					}

					if (browsePlace != null) {
						FragmentManager fragmentManager = getFragmentManager();
						FragmentTransaction fTransaction = fragmentManager
								.beginTransaction();
						fTransaction.addToBackStack(null);
						fTransaction.replace(R.id.frame_container, browsePlace)
								.commit();
						getActivity()
								.setTitle(arrPlace.get(position).getName());
					}
				}
			});
		} catch (Exception e) {
			Log.e("ListPlaceFragment : ", e.toString());
		}

		return listPlaceFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.list_place_menu, menu);

		// Associate searchable configuration with the SearchView
		searchView = (SearchView) menu.findItem(R.id.action_search_home)
				.getActionView();
		setupSearchView();
		// get my MenuItem with placeholder submenu
		MenuItem searchMenuItem = menu.findItem(R.id.action_search_home);
		// Expand the search menu item in order to show by default the query
		searchMenuItem.expandActionView();
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for items of option menu in actionbar
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		AlertDialog dialog;

		switch (item.getItemId()) {
		// show filter dialog
		case R.id.action_filter_home:

			builder.setTitle("Filter");
			oldChecked = new boolean[itemChecked.length];
			for (int i = 0; i < oldChecked.length; i++) {
				oldChecked[i] = itemChecked[i];
			}
			// set event for check item
			builder.setMultiChoiceItems(arrType, itemChecked,
					new DialogInterface.OnMultiChoiceClickListener() {

						@Override
						public void onClick(DialogInterface dialog,
								int indexSelected, boolean isChecked) {
							AlertDialog alert = (AlertDialog) dialog;
							ListView list = alert.getListView();
							// check item
							if (isChecked) {
								// checked all
								if (indexSelected == 0) {
									for (int i = 1; i < arrType.length; i++) {
										list.setItemChecked(i, true);
										itemChecked[i] = true;
									}
								}
								// checked 1 item
								else {
									boolean checkAll = false;
									itemChecked[indexSelected] = true;
									// check all item
									for (int i = 1; i < itemChecked.length; i++) {
										if (itemChecked[i] == false) {
											checkAll = false;
											break;
										} else {
											checkAll = true;
										}
									}
									if (checkAll) {
										list.setItemChecked(0, true);
										itemChecked[0] = true;
									}
								}

							} else {
								// uncheck item
								if (indexSelected == 0) {
									for (int i = 1; i < arrType.length; i++) {
										list.setItemChecked(i, false);
										itemChecked[i] = false;
									}
								} else {
									list.setItemChecked(0, false);
									itemChecked[0] = false;
									itemChecked[indexSelected] = false;
								}
							}
						}
					});

			// Set the action buttons
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							// set filter
							filter = new ArrayList<String>();
							for (int i = 1; i < itemChecked.length; i++) {
								if (itemChecked[i]) {
									filter.add(arrType[i]);
								}
							}

							// get list attraction from db
							arrPlace = homeBO.searchPlace(getKeyword(),
									getFilter(), getSorter());

							placeAdapter.setArr(arrPlace);
							placeAdapter.notifyDataSetChanged();
						}
					});
			builder.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							// Your code when user clicked on Cancel
							for (int i = 0; i < oldChecked.length; i++) {
								itemChecked[i] = oldChecked[i];
							}
						}
					});

			dialog = builder.create();
			dialog.setCancelable(false);
			dialog.show();
			break;
		case R.id.action_sort_home:
			// String[] arrSorter = new String[4];
			builder.setTitle("Sort");
			builder.setItems(getResources()
					.getStringArray(R.array.sorter_items),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int item) {
							// sort by sorter
							setSorter(getResources().getStringArray(
									R.array.sorter_items)[item]);
							arrPlace = homeBO.searchPlace(getKeyword(),
									getFilter(), getSorter());
							// reset array attraction in adapter
							placeAdapter.setArr(arrPlace);
							placeAdapter.notifyDataSetChanged();
						}
					});

			dialog = builder.create();
			dialog.setCancelable(true);
			dialog.show();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		// on resume change the title of actionbar to Attractions
		super.onResume();
		getActivity().getActionBar().setTitle("Home");
	}

	public ArrayList<String> getFilter() {
		return this.filter;
	}

	public void setFilter(ArrayList<String> filter) {
		this.filter = filter;
	}

	public String getSorter() {
		return this.sorter;
	}

	public void setSorter(String sorter) {
		this.sorter = sorter;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getKeyword() {
		return this.keyword;
	}

	private void setupSearchView() {

		searchView.setIconifiedByDefault(false);
		searchView.setQueryHint("Place Name");

		searchView
				.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
						} else if (!hasFocus) {
							onClose();
							FragmentManager fm = getFragmentManager();
							if (fm.getBackStackEntryCount() == 1) {
								fm.popBackStackImmediate();
							}
							// getFragmentManager().popBackStackImmediate();
						} else {
							onClose();
						}
					}
				});

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		setKeyword(query);
		if (getKeyword() != null && getFilter() != null && getSorter() != null) {
			arrPlace = homeBO.searchPlace(getKeyword(), getFilter(),
					getSorter());
			placeAdapter.setArr(arrPlace);
			placeAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		setKeyword(newText);
		if (getKeyword() != null && getFilter() != null && getSorter() != null) {
			arrPlace = homeBO.searchPlace(getKeyword(), getFilter(),
					getSorter());
			placeAdapter.setArr(arrPlace);
			placeAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}

	}

	@Override
	public boolean onClose() {
		// event occur when SearchView closed
		searchView.setQuery("", true);
		setKeyword("");
		arrPlace = homeBO.searchPlace("", getFilter(), getSorter());
		placeAdapter.setArr(arrPlace);
		placeAdapter.notifyDataSetChanged();

		return true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		searchView = null;
		super.onDestroy();
	}

}
